package add_$14_Case_8_5;

/*

阿拉伯数字表示筷子的编号，中文数字表示小朋友的编号
0零1一2二3三4四


 */

public class Chopstick {

    // 筷子的编号
    private int id;
    
    // 筷子的使用情况
    private boolean[] used = { false, false, false, false, false };
    
    //拿筷子的方法
    public synchronized void takeStick() {
        String sID = Thread.currentThread().getName();
        id = Integer.parseInt(sID);
        //判断
        if (id == 4) {
            if(used[id] == true || used[0] == true) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                used[id] = true;
                used[0] = true;
            }
        } else {
            if(used[id] == true || used[id+1] == true) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                used[id] = true;
                used[id+1] = true;
            }
        }
        for (int i = 0; i < used.length; i++) {
            System.out.print(used[i] + "\t" + i + "\t");
        }System.out.println();
    }
    //放下筷子的方法
    public synchronized void putStick() {
        if(id == 4) {
            used[id] = false;
            used[0] = false;
        } else {
            used[id] = false;
            used[id+1] = false;
        }
        for (int i = 0; i < used.length; i++) {
            System.out.print(used[i] + "\t" + i + "\t");
        }System.out.println();
        //唤醒等待的线程
        notifyAll();
        
    }
}
